package com.service.impl;

import com.dao.AccountDao;
import com.dao.AccountRoleDao;
import com.pojo.Account;
import com.pojo.AccountRole;
import com.pojo.SysRole;
import com.pojo.SysUser;
import com.service.AccountService;
import com.util.BCryptPasswordEncoderUtils;
import com.vo.AccountVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author mornd
 * @date 2020/11/27 - 14:35
 */
@Service
@Transactional
public class AccountServiceImpl implements AccountService {
    @Resource
    private AccountDao accountDao;
    @Autowired
    private AccountRoleDao accountRoleDao;

    //后台
    @Override
    public List<Account> findAccountList(AccountVo accountVo) {
        return accountDao.findAccountList(accountVo);
    }

    @Override
    public int updateAccount(Account account) {
        return accountDao.updateAccount(account);
    }

    @Override
    public int deleteAccount(Integer accountId) {
        return accountDao.deleteAccount(accountId);
    }


    //前台
    /**
     * 添加用户
     * @param account
     * @return
     */
    @Override
    public int addAccount(Account account) {
        account.setRegistTime(new Date());
        account.setStatus(1);
        //加密密码
        account.setPassword(BCryptPasswordEncoderUtils.encode(account.getPassword()));
        int count = accountDao.addAccount(account);
        //添加默认角色
        if(count > 0){
            accountRoleDao.addDefaultRoleByAccount(account.getId());
        }
        return count;
    }

    /**
     * 根据用户名称查询用户详情
     * @param accountName
     * @return
     */
    @Override
    public Account findAccountById(String accountName) {
        return accountDao.findAccountByName(accountName);
    }

    /**
     * 用户登录
     * @param loginName
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String loginName) throws UsernameNotFoundException {
        //根据登录名查询user
        Account loginUser = accountDao.findAccountByName(loginName);
        List<SimpleGrantedAuthority> authorities = new ArrayList<SimpleGrantedAuthority>();
        //遍历角色列表并赋值
        for (AccountRole role : loginUser.getRoleList()) {
            authorities.add(new SimpleGrantedAuthority(role.getRoleCode()));
        }
        return new User(loginUser.getLoginName(),loginUser.getPassword(),
                loginUser.getStatus() == 1,true,true,true,authorities);
    }
}
